package com.mozz.finally_work.servlet;

import com.mozz.finally_work.dao.BlogDao;
import com.mozz.finally_work.dao.TagDao;
import com.mozz.finally_work.pojo.Blog;
import com.mozz.finally_work.pojo.Tag;
import com.mozz.finally_work.utils.MybatisUtils;
import com.mozz.finally_work.utils.ParseMarkdown;
import org.apache.ibatis.session.SqlSession;
import org.pegdown.PegDownProcessor;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "TagsServlet", value = "/TagsServlet")
public class TagsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*获取参数，如果有tagId则根据id查询，没有则查询所有博客*/
        String tagId = request.getParameter("tagId");

        // 查询所有的标签
        SqlSession session = MybatisUtils.getSession();
        TagDao tagDao = session.getMapper(TagDao.class);
        List<Tag> tags = tagDao.queryAllTag();
        BlogDao blogDao = session.getMapper(BlogDao.class);
        List<Blog> blogs;
        if (tagId != null) {
            blogs = blogDao.queryBlogsByTagId(tagId);
            request.setAttribute("selected",tagId);
        }else{
            // 查询所有tag的博客
            blogs = blogDao.queryAllBlog();
        }
        session.close();
        for (Blog blog : blogs) {
            // 将 content由markdown转为html
            String parse = ParseMarkdown.parse(blog.getContent());
            blog.setContent(parse);
        }
        request.setAttribute("tags", tags);
        request.setAttribute("blogs", blogs);
        // 请求转发
        request.getRequestDispatcher("tags.jsp").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
